import axios from 'axios'
import store from '@/store'
import router from '@/router'
import Qs from 'qs'
import {
  MessageBox,
  Message
} from 'element-ui'
import {
  API_HOST
} from '@/constant'

// 全局的 axios 默认值
axios.defaults.baseURL = API_HOST; // url = base url + request url
axios.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证
axios.defaults.timeout = 0; // 指定请求超时的毫秒数(0 表示无超时时间)
axios.defaults.responseType = 'json';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

// create an axios instance
export const request = axios.create({
  transformRequest: [function(data, headers) {
    return Qs.stringify(data)
  }],
})

// request interceptor
request.interceptors.request.use(
  config => {
    //在发送请求之前做些什么
    try {
      config.headers['Authentication'] = store.getters.token;
    } catch (e) {
      console.log('发送请求之前操作失败');
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  response => {
    const res = response.data;
    const message = res.msg;
    const code = res.status;
    //接口返回异常的code
    if (code != '0') {
      //若code为-2 表示token已经失效
      if (code == '-2') {
        Message.closeAll();
        MessageBox.confirm('未登陆或登陆已超时，请重新登录', '登陆提醒', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(r => {
            router.push('/login');
          })
        })
      } else {
        Message({
          showClose: true,
          message: message === null || message === '' ? '系统忙请稍后再试' : message,
          type: 'error',
          center: true,
          duration: 3000
        })
      }
      return Promise.reject(new Error(message))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: '连接超时' || error.message,
      type: 'error',
      duration: 3000
    })
    return Promise.reject(error)
  }
)

export const requestSync = config => {
  return new Promise((resolve, reject) => {
    request(config).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

export const uploadFileSync = config => {
  const upConfig = {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authentication': store.getters.token
    }
  };
  return new Promise((resolve, reject) => {
    axios.post(config.url, config.formData, upConfig).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err);
    })
  })
}

export const downloadFile = url => {
  location.href=API_HOST+url
  // window.open(API_HOST + url)
}
